#include "esp8266.h"
#include "usart.h"
#include "lcd.h"
#include "key_led.h"
#include "file_opera.h"
#include "arm_math.h"
#include "audioplay.h"
#include <stdio.h>
#include <string.h>

#ifdef user_FreeRTOS

#include "FreeRTOS.h"
#include "semphr.h"
#include "queue.h"
#include "cmsis_os.h"

extern osSemaphoreId_t BimSem_usart3_getHandle;
extern osSemaphoreId_t BinSem_iircoe_changeHandle;
extern UART_HandleTypeDef huart3;
extern DMA_HandleTypeDef hdma_usart3_rx;
extern float32_t IIRCoeffs32LP[NUM_STAGES * 5];
uint8_t current_rx_buffer[usart_receive_len];
#define MAX_NUMBERS 10

uint8_t extract_numbers(const char *str, float32_t *numbers)
{
	const char *start = strstr(str, "CMD:");
	if (start == NULL)	return 0;
	start += 4; // 跳过 "CMD:"

	const char *end = strstr(start, ",\r\n");
	if (end == NULL)	return 0;

	int count = 0;
	char *token = strtok((char *)start, ",");
	while (token != NULL && count < MAX_NUMBERS)
	{
		numbers[count++] = (float32_t)atof(token);
		token = strtok(NULL, ",");
	}
	return count;
}

/**
 * 需要使用ESP8266发送一些信息都在该线程中执行，具有以下功能
 * 1、初始化ESP8266模块
 * 2、通过AppTask_SD_Write发来的信息，向上位机发送传输停止/出错信息
 */
void AppTask_ESP8266(void *argument)
{
	uint8_t pData[50] = "AT+CIPMUX=1\r\n";
	HAL_UARTEx_ReceiveToIdle_DMA(&huart3, current_rx_buffer, usart_receive_len);
	// HAL_NVIC_DisableIRQ(USART3_IRQn);
	HAL_UART_Transmit(&huart3, pData, strlen((char *)pData), 100);
	osDelay(pdMS_TO_TICKS(100));
	sprintf((char *)pData, "AT+CIPSERVER=1,8888\r\n");
	HAL_UART_Transmit(&huart3, pData, strlen((char *)pData), 100);
	osDelay(pdMS_TO_TICKS(100));
	// HAL_NVIC_EnableIRQ(USART3_IRQn);

	for (;;)
	{
		xSemaphoreTake(BimSem_usart3_getHandle, portMAX_DELAY);
		uint8_t result = extract_numbers((char *)current_rx_buffer, (float32_t *)IIRCoeffs32LP);
		if (result != 0)
		{	xSemaphoreGive(BinSem_iircoe_changeHandle);	}
		memset(current_rx_buffer, 0, usart_receive_len);
		osDelay(10);
	}
	/* USER CODE END AppTask_ATK8266 */
}

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
	if (huart->Instance == USART3)
	{
		__HAL_UART_CLEAR_IDLEFLAG(huart);
		HAL_UART_DMAStop(huart);
		BaseType_t xHigherPriorityTaskWoken = pdFALSE;
		xSemaphoreGiveFromISR(BimSem_usart3_getHandle, &xHigherPriorityTaskWoken);
		portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
		HAL_UARTEx_ReceiveToIdle_DMA(&huart3, current_rx_buffer, usart_receive_len);
	}
}

#else

void myESP8266_Init(void)
{
	uint8_t pData[100] = "AT+CIPMUX=1\r\n";
	HAL_UART_Transmit(&huart3, pData, sizeof(pData), 100);
	HAL_Delay(100);
	sprintf((char *)pData, "AT+CIPSERVER=1,8888\r\n");
	HAL_UART_Transmit(&huart3, pData, sizeof(pData), 100);
	HAL_Delay(100);
}
#endif
